package com.ctrip.cap.internal.appium.suite.android;

import java.io.File;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ctrip.cap.device.DeviceStore;
import com.ctrip.cap.device.android.AndroidApp;
import com.ctrip.cap.device.android.AndroidDevice;
import com.ctrip.cap.device.android.impl.DefaultAndroidApp;
import com.ctrip.cap.device.android.impl.DefaultDeviceStore;
import com.ctrip.cap.internal.appium.suite.Preprocess;
import com.ctrip.cap.internal.appium.suite.android.AppPreprocessFilter.PreprocessFilterChain;
import com.ctrip.cap.internal.suite.SuiteUtility;
import com.ctrip.cap.lanucher.AppiumConfig;

/**
 * 下载文件 为device copy 一份 submit device预处理
 * 
 * @author ltyao
 *
 */
public class AppPreprocess implements Preprocess {

	DeviceStore<AndroidDevice> deviceStore = DefaultDeviceStore.getInstance();

	private static final Logger logger = LoggerFactory
			.getLogger(AppPreprocess.class);

	private AppiumConfig appiumConfig;

	public AppPreprocess(AppiumConfig appiumConfig) {
		super();
		this.appiumConfig = appiumConfig;
	}

	@Override
	public void process() {

		String app = appiumConfig.getApp();

		int size = deviceStore.getDevices().size();
		ExecutorService executors = Executors.newFixedThreadPool(size);
		for (AndroidDevice device : deviceStore.getDevices()) {

			AppiumConfig newConfig = appiumConfig.clone();

			File appFile = SuiteUtility.constructFileName(
					device.getSerialNumber(), app);

			AndroidApp androidApp = new DefaultAndroidApp(appFile);
			final AppProcessContext context = new AppProcessContext(androidApp,
					device);
			newConfig.setApp(appFile.getAbsolutePath());

			context.setAppiumConfig(newConfig);
			context.setDevice(device);

			executors.submit(new Callable<Void>() {
				@Override
				public Void call() throws Exception {
					new PreprocessFilterChain().preprocess(context);
					return null;
				}
			});

		}
		executors.shutdown();
		try {
			executors.awaitTermination(20, TimeUnit.MINUTES);
			appiumConfig.setFullReset(false);
			// appiumConfig.set
		} catch (InterruptedException e) {
			logger.warn("suite preprocess timeout after 300", e);
		}

	}

}
